import { GET_TOKEN } from './token.js';
import ElementUI from 'element-ui';
import Vue from 'vue';
//1.引入axios
import axios from 'axios'
import router from '@/router/index.js';
//2.添加axios的默认属性请求超时时间
axios.defaults.timeout = 5000;
//3.定义基础地址
axios.defaults.baseURL = '/api'

let loading = ElementUI.Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(176, 176, 176, 0.7)'
  });

// if (process.env.NODE_ENV == "development") {
//     axios.defaults.baseURL = "/api";

// } else if (process.env.NODE_ENV == "production") {

//     axios.defaults.baseURL = "https://www.baidu.com";

// } else {
//     axios.defaults.baseURL = "https://127.3.5";
// }
//4.请求拦截
axios.interceptors.request.use((config) => {
    //1.设置token
    if (GET_TOKEN()) {
        config.headers.token = GET_TOKEN()
    }
    //2.设置请求头类型 content-type
    if (config.method == 'get') {
        config.headers["content-type"] = 'application/x-www-form-urlencoded'
    }
    if (config.method == 'post') {
        config.headers["content-type"] = 'application/json'
    }
    //设置loading效果
    loading()
    // ElementUI.Loading({
    //     lock: true,
    //     text: 'Loading',
    //     spinner: 'el-icon-loading',
    //     background: 'rgba(178, 178, 178, 0.7)'
    // });
    //对请求参数的处理
    return config
})

axios.interceptors.response.use((response) => {
    //成功回调
    //简化数据
    if (response.status == 200) {
        loading.close();
        return response.data//返回响应数据
    } else {
        return Promise.reject(response)//返回错误
    }
}, (error) => {
    //失败回调:处理http网络错误的
    //定义一个变量:存储网络错误信息
    let message = '';
    //http状态码
    let status = error.response.status;
    switch (status) {
        case 401:
            message = "TOKEN过期"
            break;
        case 403:
            message = "无权访问"
            break;
        case 404:
            message = "请求地址错误";
            break;
        case 500:
            message = "服务器出现问题"
            break;
        default:
            message = "网络出现问题";
            break;
    }
    //提示错误信息
    ElementUI.Message({
        showClose: true,
        type:"error",
        duration:3000,
        message,
        onClose(){
            if(status == 401){
                router.replace('/login')
            }
        }
    })
    return Promise.reject(error);
});
export default axios